//
//  ComposeViewController.swift
//  Weibo
//
//  Created by 冯童童 on 16/1/23.
//  Copyright © 2016年 冯童童. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {

    @objc private func selectPicture() {
        print(__FUNCTION__)
        pictureSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(KHeight / 3 * 2)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func selectEmoticon() {
        print(__FUNCTION__)
        
    }

    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func send() {
        print(__FUNCTION__)
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        let parameters = ["access_token" : UserAccountViewModel().token, "status" : textView.text]
        NetworkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            }
            
           SVProgressHUD.showSuccessWithStatus("发布成功")
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setNavBar()
        setTextView()
        setToolBar()
        setSelectorVC()
        registerNotification()
    }
  
    @objc private func keyBoardChange(n : NSNotification) {
        print(n)
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let endRect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let offsetY = -KHeight + endRect.origin.y
        UIView.animateWithDuration(duration) { () -> Void in
        self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom).offset(offsetY)
        })
            self.view.layoutIfNeeded()

        }
    }
    
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private lazy var textView : UITextView = {
        
        let tv = UITextView()
//        tv.text = "请输入新鲜事"
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        tv.backgroundColor = UIColor.greenColor()
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = .OnDrag
        tv.delegate = self
        return tv
        
    }()
    
    private lazy var placeHolderLabel : UILabel = UILabel(title: "请输入新鲜事", fontSize: 18, color: UIColor.blackColor())
    
    private lazy var toolBar : UIToolbar = UIToolbar()
    
    private lazy var pictureSelectorVC : PictureSelectorViewController = PictureSelectorViewController()
}

extension ComposeViewController : UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

extension ComposeViewController {
    
    private func setSelectorVC() {
        addChildViewController(pictureSelectorVC)
        view.addSubview(pictureSelectorVC.view)
        self.view.bringSubviewToFront(toolBar)
        pictureSelectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    
    private func setToolBar() {
        self.view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self.view)
        }
        
        var items = [UIBarButtonItem]()
        
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        
        for item in itemSettings {
            
            let imageName = item["imageName"]
            let btn = UIButton(imageName: imageName, backImageName: nil)
            if let actionName = item["actionName"] {
              btn.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            
            let item  = UIBarButtonItem(customView: btn)
            items.append(item)
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }

        items.removeLast()
        toolBar.items = items
    }
    
    private func setTextView() {
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.view.snp_top)
            make.left.right.equalTo(self.view)
            make.height.equalTo(KHeight/3)
        }
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled = false
        
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        let titleLabel = UILabel(title: "发布微博", fontSize: 17, color: UIColor.darkGrayColor())
        myView.addSubview(titleLabel)
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", fontSize: 14, color: UIColor.lightGrayColor())
        myView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(myView.snp_centerX)
            make.top.equalTo(myView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(myView.snp_centerX)
            make.bottom.equalTo(myView.snp_bottom)
        }
        navigationItem.titleView = myView
    }
}
